package com.shaw.study.springx.webmvc;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * Created by asus on 2018/5/1.
 */
public class HandlerAdapter {
    private Map<String,Integer> paramMapping;

    public HandlerAdapter(Map<String, Integer> paramMapping) {
        this.paramMapping = paramMapping;
    }

    public ModelAndView handle(HttpServletRequest req, HttpServletResponse resp, HandlerMapping handler) throws InvocationTargetException, IllegalAccessException {
        Object controller = handler.getController();
        Method method = handler.getMethod();
        //获取形参列表
        Class<?>[] types = method.getParameterTypes();
        //实参列表
        Object[] argus = new Object[types.length];
        //参数列表
        Map<String, String[]> paramMap = req.getParameterMap();
        for(Map.Entry<String, String[]> entry: paramMap.entrySet()){
            if(!paramMap.containsKey(entry.getKey())){
                continue;
            }
            String value = entry.getValue()[0];
            int index = this.paramMapping.get(entry.getKey());
            argus[index] = caseStringVal(types[index],value);
        }
        Integer reqIndex = this.paramMapping.get(HttpServletRequest.class.getName());
        Integer responseIndex = this.paramMapping.get(HttpServletResponse.class.getName());
        if(reqIndex!=null) {
            argus[reqIndex] = req;
        }
        if(responseIndex!=null) {
            argus[responseIndex] = resp;
        }

        Object result = method.invoke(controller,argus);
        if(result==null){
            return null;
        }

        Boolean isMAV = method.getReturnType() == ModelAndView.class;
        if(isMAV){
            return (ModelAndView) result;
        }else{
            return null;
        }
    }

    public Object caseStringVal(Class<?> clazz,String value){
        if(clazz == Integer.class){
            return Integer.parseInt(value);
        }
        if(clazz==String.class){
            return value;
        }
        return null;
    }
}
